package com.charles.video.gateway.filter;

import com.charles.video.common.core.constant.CacheConstants;
import com.charles.video.common.core.constant.HttpStatus;
import com.charles.video.common.core.constant.SecurityConstants;
import com.charles.video.common.core.constant.TokenConstants;
import com.charles.video.common.core.utils.JwtUtils;
import com.charles.video.common.core.utils.ServletUtils;
import com.charles.video.common.core.utils.StringUtils;
import com.charles.video.common.redis.service.RedisService;
import com.charles.video.gateway.config.properties.IgnoreWhiteProperties;
import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author Charles-H
 * 
 * 拦截路径，校验并设置信息
 */
@Component
public class AuthFilter implements GlobalFilter, Ordered {
    
    public static final Logger log = LoggerFactory.getLogger(AuthFilter.class);
    
    @Autowired
    private IgnoreWhiteProperties ignoreWhiteProperties;
    
    @Autowired
    private RedisService redisService;
    
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpRequest.Builder mutate = request.mutate();
        String url = request.getURI().getPath();
        
        /** 判断当前路径是否为白名单 */
        if (StringUtils.matches(url, ignoreWhiteProperties.getWhites())) return chain.filter(exchange);

        String token = getToken(request);
        if (StringUtils.isEmpty(token)) return unauthorizedResponse(exchange, "token令牌为空");
        
        Claims claims = JwtUtils.parseToken(token);
        if (claims == null) return unauthorizedResponse(exchange, "token令牌已过期或验证不正确");
        
        String memberKey = JwtUtils.getMemberKey(claims);
        Boolean isLogin = redisService.hasKey(getTokenKey(memberKey));

        if (!isLogin) return unauthorizedResponse(exchange, "登录已过期");

        Integer memberId = JwtUtils.getMemberId(claims);
        String memberNum = JwtUtils.getMemberNum(claims);
        String memberRole = JwtUtils.getMemberRole(claims);
        if (memberId == 0 || StringUtils.isEmpty(memberNum) || StringUtils.isEmpty(memberRole)) return unauthorizedResponse(exchange, "令牌验证失败");
        
        /** 设置用户信息至请求 */
        addHeader(mutate, SecurityConstants.MEMBER_KEY, memberKey);
        addHeader(mutate, SecurityConstants.MEMBER_ID, memberId);
        addHeader(mutate, SecurityConstants.MEMBER_NUM, memberNum);
        addHeader(mutate, SecurityConstants.MEMBER_ROLE, memberRole);
        
        /** 清除请求来源 */
        removeHeader(mutate, SecurityConstants.FROM_SOURCE);
        return chain.filter(exchange.mutate().request(mutate.build()).build());
    }
    
    /** 通过请求获取token令牌 */
    public static String getToken(ServerHttpRequest request) {
        String token = request.getHeaders().getFirst(TokenConstants.TOKEN_AUTHENTICATION);

        if (StringUtils.isNotEmpty(token) && token.startsWith(TokenConstants.TOKEN_PREFIX)) {
            token = token.replaceFirst(TokenConstants.TOKEN_PREFIX, StringUtils.EMPTY);
        }
        return token;
    }
    
    /** 获取token令牌标识 */
    private String getTokenKey(String token) {
        return CacheConstants.LOGIN_TOKEN_KEY + token;
    }
    
    /** 添加请求头 */
    private void addHeader(ServerHttpRequest.Builder mutate, String name, Object value) {
        if (value == null) return;

        String valStr = value.toString();
        String valEncode = ServletUtils.urlEncode(valStr);
        mutate.header(name, valEncode);
    }
    
    /** 移除请求头 */
    private void removeHeader(ServerHttpRequest.Builder mutate, String name) {
        mutate.headers(httpHeaders -> httpHeaders.remove(name)).build();
    }
    
    /** 异常处理 */
    private Mono<Void> unauthorizedResponse(ServerWebExchange exchange, String msg) {
        log.error("[鉴权异常]请求路径:{}", exchange.getRequest().getPath());
        return ServletUtils.webFluxResponseWriter(exchange.getResponse(), msg, HttpStatus.UNAUTHORIZED);
    }

    @Override
    public int getOrder() {
        return -200;
    }
}
